/*
 * 投我以木瓜，报之以琼琚。匪报也，永以为好也！
 * 投我以木桃，报之以琼瑶。匪报也，永以为好也！
 * 投我以木李，报之以琼玖。匪报也，永以为好也！
 * Author: Huangtiande
 * Date: 2010-03-16
 */
package com.dreamoriole.util;

import org.apache.log4j.Logger;
import java.sql.*;

public class BuildDB {	
	public static void createDatabase() {
		Connection conn = null;
		try {
			Class.forName("org.sqlite.JDBC");
			conn = DriverManager.getConnection("jdbc:sqlite:" + getDatabaseName() + ".db");
			init(conn);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		} catch (SQLException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
					log.error(e.getMessage());
				}
			}
		}
		
	}
	
	private static void init(Connection conn) {
		//禁止事务自动提交
		try {
			conn.setAutoCommit(false);
			log.info("set auto commit false");
			
			Statement stmt = null;
			stmt = conn.createStatement();
			stmt.executeUpdate("create table if not exists finance_exercises (uuid text not null unique,exercise_name text,exercise_score_criteria text,primary key (uuid));");
			stmt.executeUpdate("create table if not exists finance_questions (uuid text not null unique,question_subject text,exercise_uuid text,question_type text,primary key (uuid));");
			stmt.executeUpdate("create table if not exists finance_answers (uuid text not null unique,answer_sheet text,question_uuid text,answer_score integer,primary key (uuid))");
		} catch (SQLException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}
	
	public static String getDatabaseName() {
		return databaseName;
	}
	
	private static final String databaseName = "FreeFinance";
	private static Logger log = Logger.getLogger(BuildDB.class);
}
